//
// Created by Administrator on 2020/5/14.
//
#include "q2.h"
#include <stdio.h>
#include <malloc.h>

struct ListNode* add(struct ListNode* l1, struct ListNode* l2){
    struct ListNode *res = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *head = res;
    res->next = NULL;
    int c = 0; //add plus

    while(l1 || l2){
        int a = 0;
        int b = 0;
        struct ListNode *temp = (struct ListNode *)malloc(sizeof(struct ListNode));
        temp->next = NULL;
        if(l1) {
            a = l1->val;
            l1 = l1->next;
        }
        if(l2){
            b =  l2->val;
            l2 = l2->next;
        }

        int s = a + b + c;
        c = 0; // 恢复
        if(s >= 10) {
            c = 1;
            s = s - 10;
        }

        temp->val = s;
        res->next = temp;
        res = res->next;
    }

    if(c == 1){
        struct ListNode *temp2 = (struct ListNode *)malloc(sizeof(struct ListNode *));
        temp2->val = 1;
        temp2->next = NULL;
        res->next = temp2;
    }

    return head->next;
}

void q2(){
    struct ListNode *l1 = (struct ListNode *)malloc(sizeof(struct ListNode)), *l2 = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *n1, *n2;

    n1 = l1,n2 = l2;

    l1->next = NULL;
    l2->next = NULL;

    int lrr1[] = {2,4,3};int size1 = 3;
    int lrr2[] = {5,6,4};int size2 = 3;

    for(int i = 0; i< size1; i++){
        struct ListNode *temp1 = (struct ListNode *)malloc(sizeof(struct ListNode));
        temp1->next = NULL;
        temp1->val = lrr1[i];
        l1->next = temp1;
        l1 = l1->next;
    }

    for(int i = 0; i< size2; i++){
        struct ListNode *temp2 = (struct ListNode *)malloc(sizeof(struct ListNode));
        temp2->val = lrr2[i];
        temp2->next = NULL;
        l2->next = temp2;
        l2 = l2->next;
    }

    struct ListNode *r = add(n1->next, n2->next);

    while(r) {
        if(r->next)
            printf("%d->", r->val);
        else
            printf("%d\n", r->val);
        r = r->next;
    }
}
